<template>
    <div class="ui-dropdown">
        <div class="ui-dropdown__handle" @click="handleShowPopup">
            <slot name="handle" :item="currentItem"></slot>
        </div>
        <div class="ui-dropdown__main">
            <van-popup v-model="visible" position="bottom">
                <van-picker
                    show-toolbar
                    :columns="columns"
                    @confirm="handleConfirm"
                    @cancel="handleCancel"
                />
            </van-popup>
        </div>
    </div>
</template>
<script>
import { Popup, Picker } from 'vant'

export default {
    name: 'UiDropdown',
    components: {
        VantPopup: Popup,
        VantPicker: Picker
    },
    props: {
        value: {
            type: [String, Number]
        },
        valueField: {
            type: String,
            default: 'value'
        },
        textField: {
            type: String,
            default: 'text'
        },
        data: {
            type: Array,
            default: () => []
        }
    },
    data () {
        return {
            visible: false
        }
    },
    computed: {
        columns () {
            return this.data.map(v => v[this.textField])
        },
        currentItem () {
            return this.data.find(v => v[this.valueField] === this.value)
        }
    },
    methods: {
        handleConfirm (val) {
            const item = this.data.find(v => v[this.textField] === val)
            this.visible = false
            if (item) {
                this.$emit('input', item[this.valueField])
                this.$emit('change', {
                    item,
                    value: item[this.valueField]
                })
            }
        },
        handleCancel () {
            this.visible = false
        },
        handleShowPopup () {
            this.visible = true
        }
    }
}
</script>
<style lang="scss">
.ui-dropdown__handle{
    color: #2C9AF1;
    height: 24px;
    line-height: 24px;
    padding: 6px 0;
    box-sizing: content-box;
    &:after{
        content: '';
        display: inline-block;
        border: 5px solid #2C9AF1;
        border-left-color: transparent;
        border-right-color: transparent;
        border-bottom: 0;
        vertical-align: top;
        margin-top: 9px;
        margin-left: 1px;
    }
}
</style>